package com.example.flower_shop.controller;

import com.example.flower_shop.common.ApiResponse;
import com.example.flower_shop.dto.order.CreateOrderRequest;
import com.example.flower_shop.dto.order.OrderVO;
import com.example.flower_shop.dto.order.OrderDetailDTO;
import com.example.flower_shop.entity.CustomerOrder;
import com.example.flower_shop.entity.Product;
import com.example.flower_shop.entity.User;
import com.example.flower_shop.service.OrderService;
import com.example.flower_shop.repository.ProductRepository;
import com.example.flower_shop.exception.BusinessException;
import com.example.flower_shop.service.impl.OrderServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "订单管理")
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Validated
@Slf4j
public class OrderController {

    private final OrderService orderService;
    private final ProductRepository productRepository;

    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            log.error("用户未登录");
            throw new BusinessException("USER_NOT_AUTHENTICATED", "用户未登录");
        }
        try {
            return (Long) authentication.getPrincipal();
        } catch (Exception e) {
            log.error("无法获取用户ID: {}", e.getMessage());
            throw new BusinessException("USER_NOT_AUTHENTICATED", "无法获取用户信息");
        }
    }

    @ApiOperation("获取客户订单列表")
    @GetMapping("/customer/orders")
    public ApiResponse<Page<OrderDetailDTO>> getCustomerOrders(Pageable pageable) {
        Long userId = getCurrentUserId();
        Page<CustomerOrder> orders = orderService.getCustomerOrders(userId, pageable);
        Page<OrderDetailDTO> dtoPage = orders.map(OrderDetailDTO::new);
        return ApiResponse.success(dtoPage);
    }

    @ApiOperation("获取客户指定状态的订单")
    @GetMapping("/customer/orders/status/{status}")
    public ApiResponse<Page<OrderDetailDTO>> getCustomerOrdersByStatus(
            @PathVariable Integer status,
            Pageable pageable) {
        Long userId = getCurrentUserId();
        Page<CustomerOrder> orders = orderService.getUserOrdersByStatus(userId, status, pageable);
        Page<OrderDetailDTO> dtoPage = orders.map(OrderDetailDTO::new);
        return ApiResponse.success(dtoPage);
    }

    @ApiOperation("获取客户订单详情")
    @GetMapping("/customer/orders/{orderNo}")
    public ApiResponse<OrderDetailDTO> getCustomerOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        CustomerOrder order = orderService.getCustomerOrderByOrderNo(orderNo);
        return ApiResponse.success(new OrderDetailDTO(order));
    }

    @ApiOperation("创建客户订单")
    @PostMapping("/customer/orders")
    public ResponseEntity<ApiResponse<OrderDetailDTO>> createCustomerOrder(
            @RequestBody @Validated CreateOrderRequest createOrderRequest) {
        Long userId = getCurrentUserId();
        log.info("开始创建订单，请求数据: {}", createOrderRequest);

        try {
            // 验证商品
            for (CreateOrderRequest.OrderItemRequest item : createOrderRequest.getItems()) {
                Product product = productRepository.findById(item.getProductId())
                        .orElseThrow(() -> new BusinessException("商品不存在"));

                // 检查商品状态
                if (product.getStatus() != 1) {
                    log.warn("商品已下架，商品ID: {}, 商品名称: {}", product.getId(), product.getName());
                    throw new BusinessException(String.format("商品[%s]已下架", product.getName()));
                }

                // 检查库存
                if (product.getStock() < item.getQuantity()) {
                    log.warn("商品库存不足，商品ID: {}, 商品名称: {}, 当前库存: {}, 需求数量: {}",
                            product.getId(), product.getName(), product.getStock(), item.getQuantity());
                    throw new BusinessException(String.format("商品[%s]库存不足", product.getName()));
                }

                // 验证商品价格
                if (!product.getPrice().equals(item.getProductPrice())) {
                    log.warn("商品价格不匹配，商品ID: {}, 商品名称: {}, 实际价格: {}, 提交价格: {}",
                            product.getId(), product.getName(), product.getPrice(), item.getProductPrice());
                    throw new BusinessException(String.format("商品[%s]价格已变更，请刷新后重试", product.getName()));
                }
            }

            CustomerOrder order = orderService.createCustomerOrder(userId, createOrderRequest);
            return ResponseEntity.ok(ApiResponse.success("订单创建成功", new OrderDetailDTO(order)));
        } catch (BusinessException e) {
            log.warn("创建订单业务异常: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            log.error("创建订单系统异常: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("系统异常，请稍后重试"));
        }
    }

    @ApiOperation("支付客户订单")
    @PostMapping("/customer/orders/{orderNo}/pay")
    public ApiResponse<OrderDetailDTO> payCustomerOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        CustomerOrder order = orderService.payCustomerOrder(orderNo);
        return ApiResponse.success(new OrderDetailDTO(order));
    }

    @ApiOperation("取消客户订单")
    @PostMapping("/customer/orders/{orderNo}/cancel")
    public ApiResponse<OrderDetailDTO> cancelCustomerOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        CustomerOrder order = orderService.cancelCustomerOrder(orderNo);
        return ApiResponse.success(new OrderDetailDTO(order));
    }

    @ApiOperation("确认客户订单")
    @PostMapping("/customer/orders/{orderNo}/confirm")
    public ApiResponse<OrderDetailDTO> confirmCustomerOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        CustomerOrder order = orderService.confirmCustomerOrder(orderNo);
        return ApiResponse.success(new OrderDetailDTO(order));
    }

    @ApiOperation("删除客户订单")
    @DeleteMapping("/customer/orders/{orderNo}")
    public ApiResponse<String> deleteCustomerOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        orderService.deleteCustomerOrder(orderNo, userId);
        return ApiResponse.success("订单删除成功");
    }

    @ApiOperation("获取商家订单列表")
    @GetMapping("/merchant/orders")
    public ApiResponse<Page<OrderDetailDTO>> getMerchantOrders(Pageable pageable) {
        Long merchantId = getCurrentUserId();
        Page<CustomerOrder> orders = orderService.getMerchantOrders(merchantId, pageable);
        Page<OrderDetailDTO> dtoPage = orders.map(OrderDetailDTO::new);
        return ApiResponse.success(dtoPage);
    }

    @ApiOperation("获取商家指定状态的订单")
    @GetMapping("/merchant/orders/status/{status}")
    public ApiResponse<Page<OrderDetailDTO>> getMerchantOrdersByStatus(
            @PathVariable Integer status,
            Pageable pageable) {
        Long merchantId = getCurrentUserId();
        Page<CustomerOrder> orders = orderService.getMerchantOrdersByStatus(merchantId, status, pageable);
        Page<OrderDetailDTO> dtoPage = orders.map(OrderDetailDTO::new);
        return ApiResponse.success(dtoPage);
    }

    @ApiOperation("获取商家订单详情")
    @GetMapping("/merchant/orders/{orderNo}")
    public ApiResponse<OrderDetailDTO> getMerchantOrder(@PathVariable String orderNo) {
        Long userId = getCurrentUserId();
        CustomerOrder order = orderService.getMerchantOrderByOrderNo(orderNo);
        return ApiResponse.success(new OrderDetailDTO(order));
    }

    @ApiOperation("更新商家订单状态")
    @PutMapping("/merchant/orders/{orderNo}/status")
    public ApiResponse<OrderDetailDTO> updateMerchantOrderStatus(
            @PathVariable String orderNo,
            @RequestParam Integer status,
            @RequestParam(required = false) String processingNotes) {
        Long userId = getCurrentUserId();
        CustomerOrder order = orderService.updateMerchantOrderStatus(orderNo, status, processingNotes);
        return ApiResponse.success(new OrderDetailDTO(order));
    }

    @ApiOperation("删除商家订单")
    @DeleteMapping("/merchant/orders/{orderNo}")
    public ApiResponse<?> deleteMerchantOrder(@PathVariable String orderNo) {
        Long merchantId = getCurrentUserId();
        orderService.deleteMerchantOrder(orderNo, merchantId);
        return ApiResponse.success(null);
    }
}